package com.xgz.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.xgz.dao.TUserDao;
import com.xgz.entity.LayData;
import com.xgz.entity.TUser;
import com.xgz.service.TUserService;
import com.xgz.util.ConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

@RestController
public class TUserController {

    @Autowired
    private TUserService tUserService;
    @Autowired
    private TUserDao tUserDao;
    /**
     * 注册
     * @throws IOException
     */
    @PostMapping("add")
    private void addUser(String Username,String Password,String Passwords,Integer rid ,String sex, String status,String uploadImg) throws IOException {
        TUser tUser = new TUser();
        if (Password.equals(Passwords)) {
            tUser.setUsername(Username);
            tUser.setPassword(Password);
            tUser.setRid(rid);
            tUser.setSex(sex);
            tUser.setImgpath(uploadImg);
            if (status.equals("ture")){
                tUser.setStatus(1);
            }else{
                tUser.setStatus(2);
            }
            int b = tUserService.addUser(tUser);
        }
    }

    /**
     * 登录
     * @param session
     * @param loginUsername
     * @param loginPassword
     * @return
     * @throws IOException
     */
   @PostMapping("login")
    public LayData queryByUserName(HttpSession session,String loginUsername, String loginPassword) throws IOException {
        LayData layData = new LayData();
        TUser tUser = new TUser();
        //赋值
        tUser.setUsername(loginUsername);
        tUser.setPassword(loginPassword);
        //调用service层方法
        boolean b = tUserService.queryUser(tUser);
        if (b){
            layData.setMsg("0");
            //存值
            session.setAttribute("uname",loginUsername);
            //调用到接口方法  获取imgpath
            List<TUser> tUsers = tUserDao.queryByUserName(tUser.getUsername());
            session.setAttribute("imgpath",tUsers.get(0).getImgpath());
       }
        return layData;
   }
    /**
     * 显示所有用户
     * @param resp
     * @param id
     * @throws IOException
     */
    @RequestMapping("query")
    public void queryAll(HttpServletResponse resp,Integer id,String method ) throws IOException {
        PrintWriter writer = resp.getWriter();
        LayData layData;
        switch (method){
            case "queryById":
                boolean b = tUserService.queryById(id);
                layData = new LayData(b);
                String s = JSON.toJSONString(layData);
                writer.print(s);
                writer.flush();
                writer.close();
                break;
            case "queryAll":
                List<TUser> tUsers = tUserService.queryAll();
                layData = new LayData(tUsers);
                String s1 = JSON.toJSONString(layData);
                writer.print(s1);
                writer.flush();
                writer.close();
        }

    }

    /**
     * 上传文件到阿里云
     * @param file
     * @param request
     * @return
     */
    @PostMapping("uploadLayuiFile")
    public LayData uploadFile4(MultipartFile file, HttpServletRequest request){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConfigUtil.END_POINT;
        // oss-cn-beijing.aliyuncs.com
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConfigUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConfigUtil.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConfigUtil.BUCKET_NAME;
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        // 新的名字
        String s = UUID.randomUUID().toString();// DJKAHGFJSHGHKFSHKJDFG
        // 获取原来的文件的后缀 oldname
        String oldname=file.getOriginalFilename();
        int i = oldname.lastIndexOf(".");
        String suffixname = oldname.substring(i);
        //System.out.println("suffixname = " + suffixname);
        String newname=s+suffixname;
        //System.out.println("newname = " + newname);
        String objectName = newname;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 填写字符串。
            String content = "Hello OSS";
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
            // 上传字符串。
            ossClient.putObject(putObjectRequest);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String picpath="https://"+bucketName+"."+endpoint+"/"+objectName;
        //return "success";
        return new LayData(picpath);
    }



}
